/**
 * 
 */
package com.hk.Mgr.web.controller;

import java.util.*;

import com.hk.api.exceptions.ValidateException;
import com.hk.app.utils.RedisCilent;
import com.hk.commons.*;
import com.hk.commons.entity.product.Payment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.order.IPayment;
import com.hk.service.sys.IBank;
import com.hk.service.sys.ISysUser;

/**
 * 更新用户的绑卡信息
 * 
 * @author
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/paymentCtrl")
public class 	PayMentMethodCtrl extends BaseCtrl {

	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private IBank bankService;

	@Autowired
	private YingmiApiUtils utils;

	@Autowired
	private IPayment paymentService;

	@ResponseBody
	@RequestMapping(value = "/getFromYM", method = RequestMethod.GET)
	public ResponseBase<Boolean> getFromYM() {
		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
		Map<String, String> params = new HashMap<>();

		List<SysUser> userList = sysUserService.getAll();

		for (SysUser user : userList) {
			String brokerUserId = user.getName();
			String accountId = user.getAccountId();

			if (StringHelper.isNotEmpty(brokerUserId)
					&& StringHelper.isNotEmpty(accountId)) {
				logger.info("brokerUserId = " + brokerUserId + "  accountId = "
						+ accountId);
				params.put("brokerUserId", brokerUserId);
				params.put("accountId", accountId);
				String charset = utils
						.get("/account/getPaymentMethods", params);

				org.codehaus.jackson.JsonNode result = JsonUtils
						.toJsonObject(charset);
				logger.info("result = " + charset);

				if (result.get("msg") != null) {
					logger.info("message is not exist!");
					logger.info("retuen message : " + charset);
				} else {
					ObjectMapper objectMapper = new ObjectMapper();
					List<LinkedHashMap<String, Object>> lhm = null;
					try {
						lhm = objectMapper.readValue(charset, List.class);
						for (LinkedHashMap<String, Object> lkm : lhm) {
							if (lkm.get("paymentMethodId") != null) {
								logger.info("paymentMethodId = "
										+ String.valueOf(lkm
												.get("paymentMethodId")));
								logger.info("phone = "
										+ String.valueOf(lkm.get("phone")));
								logger.info("paymentType = "
										+ String.valueOf(lkm.get("paymentType")));
								logger.info("paymentNo = "
										+ String.valueOf(lkm.get("paymentNo")));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}

		}
		resp.setResult(true);
		return resp;
	}


	/**
	 * 查询支付方式
	 * @param userId
	 * @type 是否包括已解绑的卡，0否，1是，默认为0
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getPaymentMethodList", method = RequestMethod.GET)
	public ResponseBase<List<Payment>> getPaymentMethodList(@RequestParam Long userId,String token){
		ResponseBase<List<Payment>> result = new ResponseBase<>();
		List<Payment> list = new ArrayList<>();

		if(!RedisCilent.existsKey(CacheConstants.VALIDATE_TOKEN+token) || !RedisCilent.getString(CacheConstants.VALIDATE_TOKEN+token).equals(userId.toString())){
			result.setMsg("TOKEN不存在！");
			result.setResultCode(ResultCode.ILLEGAL_TOKEN.getCode());
			//result.setResult(list);
			return result;
		}

		SysUser user = sysUserService.findById(userId);

		if(user == null){
			result.setMsg("用户不存在！");
			result.setResultCode(ResultCode.PARAM_ERROR.getCode());
			result.setResult(list);
			return result;
		}


		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId",userId);
		list = paymentService.findByFilter(hqlFilter);
		result.setResult(list);
		return result;
	}

	/**
	 * 查询盈米支付方式
	 * @param userId
	 * @param paymentMethodId
	 * @param token
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getYingMiPaymentMethod", method = RequestMethod.GET)
	public ResponseBase<Payment> getYingMiPaymentMethod(@RequestParam Long userId,String paymentMethodId,String token){
		ResponseBase<Payment> result =new ResponseBase();
		if(!RedisCilent.existsKey(CacheConstants.VALIDATE_TOKEN+token) || !RedisCilent.getString(CacheConstants.VALIDATE_TOKEN+token).equals(userId.toString())){
			result.setMsg("TOKEN不存在！");
			result.setResultCode(ResultCode.ILLEGAL_TOKEN.getCode());
			return result;
		}

		SysUser user = sysUserService.findById(userId);

		if(user == null){
			result.setMsg("用户不存在！");
			result.setResultCode(ResultCode.PARAM_ERROR.getCode());
			return result;
		}

		List<Payment> list ;
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId",userId);
		hqlFilter.addEQFilter("paymentMethodId",paymentMethodId);
		list = paymentService.findByFilter(hqlFilter);
		if(list == null || list.isEmpty()){
			result.setResultCode(ResultCode.NO_DATA.getCode());
			result.setMsg(ResultCode.NO_DATA.getMsg());
		}else {
			result.setResult(list.get(0));
		}
		return result;
	}
	// @ResponseBody
	// @RequestMapping(value = "/updFromYMByUser", method = RequestMethod.POST)
	// public ResponseBase<Boolean> updFromYMByUser(@RequestBody SysUser req) {
	// ResponseBase<Boolean> resp = new ResponseBase<Boolean>();
	// Map<String, String> params = new HashMap<>();
	//
	// String brokerUserId = req.getName();
	// String accountId = req.getAccountId();
	//
	// if (StringHelper.isNotEmpty(brokerUserId)
	// && StringHelper.isNotEmpty(accountId)) {
	// SysUser user = sysUserService.getByAccountId(accountId);
	//
	// if (user != null) {
	//
	// logger.info("brokerUserId = " + brokerUserId + "  accountId = "
	// + accountId);
	// params.put("brokerUserId", brokerUserId);
	// params.put("accountId", accountId);
	// String charset = utils
	// .get("/account/getPaymentMethods", params);
	//
	// org.codehaus.jackson.JsonNode result = JsonUtils
	// .toJsonObject(charset);
	// logger.info("result = " + charset);
	//
	// if (result.get("msg") != null) {
	// logger.info("message is not exist!");
	// logger.info("retuen message : " + charset);
	// } else {
	// ObjectMapper objectMapper = new ObjectMapper();
	// List<LinkedHashMap<String, Object>> lhm = null;
	// try {
	// lhm = objectMapper.readValue(charset, List.class);
	// for (LinkedHashMap<String, Object> lkm : lhm) {
	// if (lkm.get("paymentMethodId") != null) {
	// String paymentMethodId = String.valueOf(lkm
	// .get("paymentMethodId"));
	// String phone = String.valueOf(lkm.get("phone"));
	// String paymentType = String.valueOf(lkm
	// .get("paymentType"));
	// String paymentNo = String.valueOf(lkm
	// .get("paymentNo"));
	// Integer bankId = null;
	// String bankCode = null;
	//
	// if (paymentType.startsWith("bank:")) {
	// String str[] = paymentType.split(":");
	// String yimiBankCode = str[1];
	// bankCode = YimiBankCodeHelp
	// .BankCodeMap(yimiBankCode);
	// bankId = bankService
	// .getBankIdByCode(bankCode);
	// }
	//
	// Payment pay = new Payment();
	// pay.setPaymentMethodId(paymentMethodId);
	// pay.setPhone(phone);
	// pay.setPaymentNo(paymentNo);
	// pay.setBankId(bankId);
	// pay.setUserId(user.getId());
	// pay.setAccountName(user.getRealName());
	// pay.setIdentityNo(user.getIdentity());
	// pay.setCardStatus(ConstantPaymentDisplay.PAYMENT_DISPLAY_SHOW);
	// paymentService.add(pay);
	//
	// logger.info("paymentMethodId = "
	// + String.valueOf(lkm
	// .get("paymentMethodId")));
	// logger.info("phone = "
	// + String.valueOf(lkm.get("phone")));
	// logger.info("paymentType = "
	// + String.valueOf(lkm.get("paymentType")));
	// logger.info("paymentNo = "
	// + String.valueOf(lkm.get("paymentNo")));
	// }
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	// }
	// }
	// resp.setResult(true);
	// return resp;
	// }

}
